package com.ty.wx.controller;

import com.ty.bean.*;
import com.ty.mvc.ResponseBody;
import com.ty.service.BaseExpressService;
import com.ty.service.impl.BaseExpressServiceImpl;
import com.ty.util.DateFormatUtil;
import com.ty.util.JSONUtil;
import com.ty.util.RandomUtil;
import com.ty.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.PublicKey;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author 田野
 */
public class ExpressController {
    private BaseExpressService expressService = new BaseExpressServiceImpl();
    @ResponseBody("/wx/findExpressByUserPhone.do")
    public String findByUserPhone(HttpServletRequest request, HttpServletResponse response){

        Courier wxCourier = UserUtil.getWxCourier(request.getSession());
        User wxUser = UserUtil.getWxUser(request.getSession());
        String userPhone = null;

        if (wxUser != null){
            userPhone = wxUser.getPhone();
        }

        if (wxCourier != null){
            userPhone = wxCourier.getPhone();
        }

        System.out.println(userPhone);

        List<Express> list = expressService.findByUserPhone(userPhone, 2);
        List<BootStrapTableExpress> list2 = new ArrayList<>();
        for (Express express : list) {
            BootStrapTableExpress bootStrapTableExpress = new BootStrapTableExpress();
            bootStrapTableExpress.setId(express.getId());
            bootStrapTableExpress.setNumber(express.getNumber());
            bootStrapTableExpress.setUsername(express.getUsername());
            bootStrapTableExpress.setUserPhone(express.getUserPhone());
            bootStrapTableExpress.setCompany(express.getCompany());

            if (express.getCode() != null){
                bootStrapTableExpress.setCode(express.getCode());
            }else {
                bootStrapTableExpress.setCode("已取件");
            }
            // 日期工具类进行日期格式化
            bootStrapTableExpress.setInTime(DateFormatUtil.format(express.getInTime()));
            if (express.getOutTime() != null){
                bootStrapTableExpress.setOutTime(DateFormatUtil.format(express.getOutTime()));
            }else {
                bootStrapTableExpress.setOutTime("待取件");
            }
            bootStrapTableExpress.setSysPhone(express.getSysPhone());
            Integer status = express.getStatus();
            if (status == 0){
                bootStrapTableExpress.setStatus("待取");
            }else if (status == 1){
                bootStrapTableExpress.setStatus("已取");
            }else {
                bootStrapTableExpress.setStatus("" + express.getStatus());
            }
            list2.add(bootStrapTableExpress);
        }

        System.out.println(list.size());
        Message message = new Message();

        if (list2.size() != 0){
            Stream<BootStrapTableExpress> unFetchedExpresses = list2.stream().filter(express -> {
                if ("待取".equals(express.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2)->{

                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());

                // 根据返回值的正负进行排序  降序排列
                return (int) (o1Time-o2Time);

            });

            Stream<BootStrapTableExpress> fetchedExpresses = list2.stream().filter(express -> {
                if ("已取".equals(express.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2)->{
                long o1Time = DateFormatUtil.toTime(o1.getOutTime());
                long o2Time = DateFormatUtil.toTime(o2.getOutTime());
                // 根据返回值的正负进行排序  降序排列
                return (int) (o1Time-o2Time);

            });

            Object[] s0 = unFetchedExpresses.toArray();
            Object[] s1 = fetchedExpresses.toArray();

            Object[] data = new Object[]{s0, s1};
            // 是真的方便啊，也节省了空间
            Map<String, Object[]> map = Map.of("s0", s0, "s1", s1);

            message.setStatus(0);
            message.setData(map);

        }else {
            message.setStatus(-1);
        }

        String json = JSONUtil.toJSON(message.getData());
        return json;

        /*IntStream.range(0,10).forEach(System.out::println);*/

    }

    @ResponseBody("/wx/userExpressList.do")
    public String expressList(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");

        List<Express> list = expressService.findByUserPhone(userPhone, 0);
        List<BootStrapTableExpress> list1 = new ArrayList<>();
        Message message = new Message();

        if (list.size()==0){
            // 当前号码对应的用户没有待取件快递信息
            message.setStatus(-1);
            message.setResult("未找到相关的快递信息！");

        }else {
            // 当前号码对应的用户有待取件快递信息
            message.setStatus(0);
            message.setResult("查询成功！");
            for (Express express : list) {
                BootStrapTableExpress bootStrapTableExpress = new BootStrapTableExpress();
                bootStrapTableExpress.setId(express.getId());
                bootStrapTableExpress.setNumber(express.getNumber());
                bootStrapTableExpress.setUsername(express.getUsername());
                bootStrapTableExpress.setUserPhone(express.getUserPhone());
                bootStrapTableExpress.setCompany(express.getCompany());
                bootStrapTableExpress.setCode(express.getCode());
                Timestamp inTime = express.getInTime();
                String formatInTime = DateFormatUtil.format(new Date(inTime.getTime()));
                bootStrapTableExpress.setInTime(formatInTime);
                bootStrapTableExpress.setSysPhone(express.getSysPhone());
                bootStrapTableExpress.setStatus("待取件");
                list1.add(bootStrapTableExpress);
            }
            message.setData(list1);
            System.out.println("(快递员操作的)封装快递类长度：" + list1.size());
        }



        String json = JSONUtil.toJSON(message);
        return json;

    }

    @ResponseBody("/wx/updateStatus.do")
    public String updateStatus(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");

        Express byCode = expressService.findByCode(code);

        boolean flag = expressService.updateStatus(byCode.getNumber());

        Message message = new Message();

        if (flag){
            message.setStatus(0);
            message.setResult("已成功取件！");

        }else {
            message.setStatus(-1);
            message.setResult("取件码不存在，请用户更新二维码！");
        }

        String json = JSONUtil.toJSON(message);
        return json;

    }

    @ResponseBody("/wx/findExpressByCode.do")
    public String findExpressByCode(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        Express express = expressService.findByCode(code);
        Message message = new Message();

        if (express != null){
            message.setStatus(0);
            message.setResult("查询成功！");
            BootStrapTableExpress bootStrapTableExpress = new BootStrapTableExpress();
            bootStrapTableExpress.setId(express.getId());
            bootStrapTableExpress.setNumber(express.getNumber());
            bootStrapTableExpress.setUsername(express.getUsername());
            bootStrapTableExpress.setUserPhone(express.getUserPhone());
            bootStrapTableExpress.setCompany(express.getCompany());
            bootStrapTableExpress.setCode(express.getCode());
            bootStrapTableExpress.setInTime(DateFormatUtil.format(new Date(express.getInTime().getTime())));
            bootStrapTableExpress.setSysPhone(express.getSysPhone());
            Timestamp outTime = express.getOutTime();
            bootStrapTableExpress.setOutTime(outTime==null?"未出库":DateFormatUtil.format(outTime));

            message.setData(bootStrapTableExpress);
        }else {
            message.setStatus(-1);
            message.setResult("取件码不存在！");
        }

        String json = JSONUtil.toJSON(message);
        return json;
    }

    @ResponseBody("/wx/findExpressByNumber.do")
    public String findExpressByNum(HttpServletRequest request, HttpServletResponse response){

        String expressNum = request.getParameter("expressNum");
        Express express = expressService.findByNumber(expressNum);
        Message message = new Message();
        if (express != null){
            // 有此单号的快递
            message.setStatus(0);
            message.setResult("查询成功！");
            BootStrapTableExpress bootStrapTableExpress = new BootStrapTableExpress();
            bootStrapTableExpress.setId(express.getId());
            bootStrapTableExpress.setNumber(express.getNumber());
            bootStrapTableExpress.setUsername(express.getUsername());
            bootStrapTableExpress.setUserPhone(express.getUserPhone());
            bootStrapTableExpress.setCompany(express.getCompany());
            bootStrapTableExpress.setCode(express.getCode()!=null?express.getCode():"已取件");
            bootStrapTableExpress.setInTime(DateFormatUtil.format(new Date(express.getInTime().getTime())));
            bootStrapTableExpress.setSysPhone(express.getSysPhone());
            Timestamp outTime = express.getOutTime();
            bootStrapTableExpress.setOutTime(outTime==null?"未出库":DateFormatUtil.format(outTime));

            HttpSession session = request.getSession();
            session.setAttribute("indexFindExpressByNum", bootStrapTableExpress);

        }else {
            // 没有此单号的快递
            message.setStatus(-1);
            message.setResult("取件码不存在！");
        }

        String json = JSONUtil.toJSON(message);
        return json;
    }

    @ResponseBody("/wx/wxAddExpress.do")
    public String addExpress(HttpServletRequest request, HttpServletResponse response){
        String expressId = request.getParameter("expressId");
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String company = request.getParameter("company");

        String sysPhone = UserUtil.getUserPhone(request.getSession());
        String code = RandomUtil.getCode();
        Express express = new Express();

        express.setNumber(expressId);
        express.setUsername(username);
        express.setUserPhone(phone);
        express.setCompany(company);
        express.setSysPhone(sysPhone);
        express.setCode(code);

        Message message = new Message();

        boolean insert = expressService.insert(express);

        if (insert){
            //新增成功
            message.setStatus(0);
            message.setResult("新增成功！");
        }else {
            // 新增失败
            message.setStatus(-1);
            message.setResult("新增成功！");
        }

        String json = JSONUtil.toJSON(message);

        return json;

    }


}
